package com.cooperation;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AwaitSignalExample {

    private Lock lock=new ReentrantLock();

    private Condition condition=lock.newCondition();


    /**
     * java.util.concurrent类中库提供看Condition类来实现线程之间的协调，可在Condition上调用await()方法使线程等待，其他线程调用signal()和signalAll()方法唤醒等待的线程。
     * 相比于wait()这种等待方式，await()可以指定等待的条件，因此更加灵活
     */
    public void before(){
        lock.lock();
        try {
            System.out.println("before");
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void after(){
        lock.lock();
        try {
            condition.await();
            System.out.println("after");
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService= Executors.newCachedThreadPool();
        AwaitSignalExample awaitSignalExample=new AwaitSignalExample();
        executorService.execute(()-> awaitSignalExample.after());
        executorService.execute(()-> awaitSignalExample.before());

    }

}
